package social;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import message.FriendRequest;

/**
 * Servlet implementation class RequestServlet
 */
@WebServlet("/RequestServlet")
public class RequestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RequestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SocialDBC db = (SocialDBC) getServletContext().getAttribute("database");
		
		String action = request.getParameter("action");
		String toUser = request.getParameter("toUser");
		String fromUser = request.getParameter("fromUser");
		
		HttpSession session = request.getSession();
		
		if (action.equals("accept")) {
			//make friends
			try {
				int id = Integer.parseInt(request.getParameter("id"));
				db.setMailViewed(id);
			} catch (Exception e) {}
			db.addFriend(toUser, fromUser);
			//request.setAttribute("profileName", fromUser);
			session.setAttribute("profileName", fromUser);
			//request.getRequestDispatcher("user-profile.jsp").forward(request, response);
		} else if (action.equals("request")) {
			//send friend request
			if (db.friendRequestSent(toUser, fromUser) || db.friendRequestSent(fromUser, toUser)) {
				session.setAttribute("profileName", fromUser);
			} else {
				FriendRequest req = new FriendRequest(toUser, fromUser);
				db.addMail(req);
				//request.setAttribute("profileName", toUser);
				session.setAttribute("profileName", toUser);
			}
			//request.getRequestDispatcher("user-profile.jsp").forward(request, response);
		} else if (action.equals("remove")) {
			db.removeFriend(toUser, fromUser);
			db.removeMail(toUser, fromUser, "request");
			session.setAttribute("profileName", toUser);
		} else if (action.equals("reject")) {
			db.removeMail(fromUser, toUser, "request");
			session.setAttribute("profileName", fromUser);
		}
		request.getRequestDispatcher("user-profile.jsp").forward(request, response);
//		//System.out.println(String.format("action:%s toUser:%s fromUser:%s", action, toUser, fromUser));
	}
}
